<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class User extends CI_Controller {
	function __construct() {
		parent::__construct ();
		#load lang
		$this->load->library('Form_validation');
		$this->load->model('User_model');
		$this->load->helper('url');
		$this->load->library('antispam');
		$this->load->library('hash');
		$this->load->model('Place_model');
		
        #load model
	}
	public function register()
	{
		$this->form_validation->set_rules('userName','UserName','trim|required|alpha_numeric|min_length[6]|callback_user_not_exites');
		if($this->form_validation->run()==false){
			$this->load->view('view_register');
		}else
		{
			$userName=$this->input->post('userName');
			$this->User_model->register_user($userName,$userName);
		}		
	}
	/*---------------------Bat dau Xem tat ca cac ban ghi--------------------------*/
	public function getAll()
	{
		/*------------------------------------------------------------------------------*/
		if(isset($_POST['page']))
			$page =$_POST['page'] ; // get the requested page
		else $page=1;
		if(isset($_POST['rows']))
			$limit=$_POST['rows'];// get how many rows we want to have into the grid
		else $limit = 1;
		if(isset($_POST['sidx']))
			$sidx=$_POST['sidx'];// get index row - i.e. user click to sort
		else $sidx = 'id';
		if(!$sidx) $sidx ='id';
		if(isset($_POST['sord']))
			$sord=$_POST['sord'];// get the direction
		else $sord= 'asc';
		$total_pages=0;
		$user_Id=$this->session->userdata('sessionId');
		
		
		$where='user_id ='.$user_Id;
		$by=$sord;
		$order=$sidx;
		//echo 'sap xep:'.$sidx;
		//echo 'thu thu:'.$sord;
	
		$count = count($this->Place_model->get("id", $where));
		if( $count >0 ) {
			$total_pages = ceil($count/$limit);
		} else { $total_pages = 0;
		}
		if ($page > $total_pages) $page=$total_pages;
		$start = $limit*$page - $limit; // do not put $limit*($page - 1)
	
		$select = "id, title, description, createddate,price,typeid";
		$result = $this->Place_model->fetch($select, $where, $sidx, $sord, $start, $limit);
			
		$responce->page = $page;
		$responce->total = $total_pages;
		$responce->records = $count;
		$i=0;
		foreach($result as $userArray)
		{
			$responce->rows[$i]['id']=$userArray->id;
			$responce->rows[$i]['cell']=array($userArray->id,$userArray->title,$userArray->description,$userArray->createddate,number_format($userArray->price),$userArray->typeid);
			$i++;
		}
		echo json_encode($responce);
	}
	/*---------------------Ket thuc Xem tat ca cac ban ghi--------------------------*/
	
	/*-----------------------Bat dau xu ly thong tin: them sua xoa...-------------*/
	public function process()
	{
		$act=$this->filter->injection_html($this->input->post('act'));
		switch ($act) 
		{
		    case "add"://add
		        $this->add();
		        break;
		    case "commonEdit"://edit common
		        $this->commonEdit();
		        break;
		    case "expandEdit"://edit expand
		        $this->expandEdit();
		        break;
		    case "logout"://logout
		        $this->logout();
		        break;
		    case "captcha"://Lay captcha
		        $this->getCaptcha();
		        break;
		    case "email"://check email
		        $this->check_Email();
		        break;
		    case "checkSession"://check session
		        $this->checkRole();
		        break;
		    default:
		     	echo md5(rand(1, 1000000));//No process if hack
		}
	}
	/*-----------------------Ket thuc xu ly thong tin: them sua xoa...-------------*/
	private function add()
	{
		$capcha_edit  =trim($this->filter->injection_html($this->input->post('captcha_edit')));
		$answers = $this->session->userdata('word');
		if($capcha_edit==$answers)
		{
			$regisdate = mktime(0, 0, 0, date('m'), date('d'), date('Y'));
			$this->load->library('hash');
			$salt = $this->hash->key(8);
			$dataAdd = array(
					'use_username'      =>      trim(strtolower($this->filter->injection_html($this->input->post('email_edit')))),
					'use_password'      =>      $this->hash->create($this->input->post('password_edit'), $salt, 'md5sha512'),
					'use_salt'          =>      $salt,
					'use_email'         =>      trim(strtolower($this->filter->injection_html($this->input->post('email_edit')))),
					'use_fullname'      =>      trim($this->filter->injection_html($this->input->post('fullName_edit'))),
					'use_mobile'        =>      trim($this->filter->injection_html($this->input->post('mobil_edit'))),
					'use_group'         =>      '1',
					'use_status'        =>      '1',
					'use_regisdate'     =>      $regisdate,
					'use_enddate'       =>      '',
					'use_key'           =>      $this->hash->create($this->input->post('email_edit'), $this->input->post('email_edit'), 'sha256md5'),
					'use_lastest_login' =>      ''
			);
			if($this->User_model->add($dataAdd))
			{
				$responce->status=session_id();
				$responce->ret='success';
				echo json_encode($responce);
			}else
			{
				$responce->status=session_id();
				$responce->ret='failure';
				echo json_encode($responce);
			}
		}
		else
		{
			$responce->status=session_id();
			$responce->ret='noCaptcha';
			echo json_encode($responce);
		}
	}
		//Check user and Pass
   private function check_Email_Pass($email,$pass)
	{
		$where="use_email = '$email'";
		$sql="use_password,use_salt";
		$userArray=$this->User_model->get($sql, $where);
		if(count($userArray) == 1)
		{
			$salt=$userArray->use_salt;
			$yourPass=$userArray->use_password;
			$passCheck=$this->hash->create($pass, $salt, 'md5sha512');
			
			if($yourPass==$passCheck)
				return true;
		    else 
		    	return false;
		}
			return false;
	}
 private function commonEdit()
	{
		$capcha_edit  =trim($this->filter->injection_html($this->input->post('captcha_edit')));
		$answers = $this->session->userdata('word');
		if($capcha_edit==$answers)
		{
			$email=$this->filter->injection_html($this->input->post('email'));
	    	$user_Email=$this->session->userdata('sessionEmail');
	   
	    	if(!isset($user_Email)&& $email!=$user_Email)
	    		$user_Email="notFound";
	    	$where="use_email = '$user_Email'";
	    	$changePass=$this->filter->injection_html($this->input->post('changePass'));
	    	if($changePass=='on')//co ca yeu cau doi mat khau
	    	{
	    		$oldPass=$this->filter->injection_html($this->input->post('password_edit'));
	    		//kiem tra mat khau cu co dung khong:
	    		if($this->check_Email_Pass($user_Email,$oldPass))
	    		{
	    			$salt = $this->hash->key(8);
	    			$dataEdit = array
					(
						'use_fullname'      =>      trim($this->filter->injection_html($this->input->post('fullName_edit'))),
						'use_mobile'        =>      trim($this->filter->injection_html($this->input->post('mobil_edit'))),
						'use_password'      =>      $this->hash->create($this->input->post('passwordNew_edit'), $salt, 'md5sha512'),
						'use_salt'          =>      $salt
					);
		
	    		}else
	    		{
	    			$responce->status=session_id();
					$responce->ret='invalid';
					$responce->session='notFound';
			 		echo json_encode($responce);
			 		return;
	    		}
	    	}else//khong can doi mat khau - chi thay doi thong tin co ban
	    	{
				$dataEdit = array
				(
					'use_fullname'      =>      trim($this->filter->injection_html($this->input->post('fullName_edit'))),
					'use_mobile'        =>      trim($this->filter->injection_html($this->input->post('mobil_edit')))
				);	
	    	}
		    if($this->User_model->update($dataEdit, $where))
			{
				$responce->status=session_id();
				$responce->ret='success';
			 	echo json_encode($responce);
			 }else
			 {
			 	$responce->status=session_id();
				$responce->ret='failure';
			 	echo json_encode($responce);
			 }
		}else 
		{
			$responce->status=session_id();
			$responce->ret='noCaptcha';
			echo json_encode($responce);
		}	
	}
	private function expandEdit()
	{
			$email=$this->filter->injection_html($this->input->post('email'));
			$user_Email=$this->session->userdata('sessionEmail');
	
			if(!isset($user_Email)&& $email!=$user_Email)
				$user_Email="notFound";
			$where="use_email = '$user_Email'";
			$dataEdit = array(
				'use_sex'           =>      (int)$this->input->post('gender_edit'),
				'use_address'       =>      trim($this->filter->injection_html($this->input->post('address_edit'))),
				'use_province'      =>      (int)$this->input->post('city_edit'),
				'use_yahoo'         =>      trim($this->filter->injection_html($this->input->post('yahoo_edit'))),
				'use_skype'         =>      trim($this->filter->injection_html($this->input->post('sky_edit')))
		 );
			
			if($this->User_model->update($dataEdit, $where))
			{
				$responce->status=session_id();
				$responce->ret='success';
				echo json_encode($responce);
			}else
			{
				$responce->status=session_id();
				$responce->ret='failure';
				echo json_encode($responce);
			}
		
	}
	/**
	 * Check Email Exites
	 */
    private function check_Email()
	{
		$email=trim(strtolower($this->filter->injection_html($this->input->post('email_edit'))));

		if($this->User_model->check_Email($email))
		{
			$responce->status=session_id();
			$responce->ret='success';
			echo json_encode($responce);
		}else
		{
			$responce->status=session_id();
			$responce->ret='failure';
			echo json_encode($responce);
		}
	}


	private function user_not_exites($userName)
	{
		$this->form_validation->set_message('user_not_exites','Da ton tai');
		if($this->User_model->check_user($userName))
		{
			return false;
		}else
			return true;
	}
	/**
	 * Check Role
	 */
   private function checkRole()
	{
	   if(!$this-> is_logined($this->session->userdata('sessionUser')))
		{
			$this->session->sess_destroy();
			$responce->ret='notLogin';
			$responce->secure=rand(1, 1000000);
			$responce->checkCode=rand(1, 1000000);  
			echo json_encode($responce);
			die();
		}else
		{
			$responce->ret=rand(1, 1000000);
			$responce->secure=rand(1, 1000000);
			$responce->checkCode=rand(1, 1000000);  
			echo json_encode($responce);
		}
	}
	/**
	 * Check Login
	 * @param unknown_type $user
	 * @param unknown_type $group
	 * @param unknown_type $type
	 */
	private function is_logined($user, $group='', $type = 'admin')
	{
		switch(strtolower($type))
		{
			case 'admin':
			    if($user && trim($user) != '' && $user ='thang' )
			    {
					return true;
			    }
			    break;
			case 'home':
			    if($user && trim($user) != '' && $user ='userHome')
			    {
					return true;
			    }
			    break;
		}
		return false;
	}
	/**
	 * logout 
	 */
	public function logout()
	{
		$this->session->sess_destroy();
		redirect(base_url().'index/place', 'location');
	}
	/**
	 * login Home user
	 */
	public function login()
	{ 
		$k= $this->input->post('pass');
		//load session library
		if(!$this->session) $this->load->library('session');
		$ssid=session_id();
		$id='notok';
		$user='notFound ';
		$pass='notFound';
		if(isset($_POST["id"]))
			$id=$_POST['id'];
		if(isset($_POST["user"]))
			$user=$this->filter->injection_html($this->input->post('user'));
		if(isset($_POST["pass"]))
			$pass=$this->filter->injection_html($this->input->post('pass'));
		$value = explode("@", $user);
		
		if($ssid==$id)
		{
			
			$where="use_email = '$user'";
			$sql="use_id,use_password, use_username,use_salt, use_fullname, use_email";
			$userArray=$this->User_model->get($sql, $where);
			$chk=false;
			if(count($userArray) == 1)
			{
				$salt=$userArray->use_salt;
				$yourPass=$userArray->use_password;
				$passCheck=$this->hash->create($pass, $salt, 'md5sha512');
					
				if($yourPass==$passCheck)
					$chk= true;
				else
					$chk= false;
			}
			
			if($chk==false)
			{
				$md5=md5($ssid.rand());
				$member = array('Login' => 'Sai thong tin TDN OR MK',
						'pass' => 'xxxxxx',
						'sessionKey' => md5(rand(1, 1000000)),
						'checkCode'  =>rand(1, 1000000),
						'status'=>$md5);
				$this->session->sess_destroy();//Huy session
				echo json_encode($member);
			}
			else
			{
				//$responce=array($userArray->use_id,$userArray->use_username,$userArray->use_fullname,$userArray->use_email,$userArray->use_address,$userArray->use_phone,$userArray->use_yahoo);
				
				$md5=md5($ssid.'OK');
				$member = array('Login' => 'Thanh cong',
						'pass' => 'xxxxxx',
						'sessionKey' => md5(rand(1, 1000000)),
						'checkCode'  =>md5($user),
						'status'=>$md5);
				
				$sessionLogin = array(
						'sessionUser'  =>      'userHome',
						'sessionName'  =>      $value[0],
						'sessionEmail' =>      $user,
						'sessionkey'   =>      $ssid,
						'sessionId'   =>      $userArray->use_id
				);
				$this->session->set_userdata($sessionLogin);
				echo json_encode($member);
				//redirect(base_url().'index/place', 'location');
			}
		} else
		{
			echo 'File not found!';
		}
	}
	/**
	 * 
	 */
	private function getCaptcha()
    {
    	$configs = array(
					'img_path' => './themes/home/captcha/',
					'img_url' => base_url() . 'themes/home/captcha/',
					'img_height' => '30',
				);
		$captcha = $this->antispam->get_antispam_image($configs);
		$this->session->set_userdata($captcha);
		
		//$data['cap_img']=$cap['image'];
		///$this->load->view('form_view',$data);
		
		$responce->ret = 'success';
		$responce->url = $captcha['image'];
		$responce->status=session_id();
		
		echo json_encode($responce);
    }
    /**
     * Check valid captcha
     * @param $string
     */
    private function check_captcha( $string )
    {
    	$user_answer = md5(strtolower(trim($string)));
    	$answers = $this->session->userdata('captcha_answers');
    
    	if( in_array($user_answer, $answers) )
    	{
    		return TRUE;
    	}
    	else
    	{
    		$this->form_validation->set_message('check_captcha', 'Your answer was incorrect!');
    		return FALSE;
    	}
    }
    //Lay thong tin 1 thanh vien
    public function getOne()
    {
    	$email=$this->filter->injection_html($this->input->post('email'));;
    	$user_Email=$this->session->userdata('sessionEmail');
    	if(!isset($user_Email)&& $email!=$user_Email)
    		$user_Email="notFound";
    	$start=0;
    	$limit=1;
    	$sidx='';
    	$sord='';
    	$where="use_email='".$user_Email."'";
    	$select = "use_id, use_username, use_fullname, use_email, use_address,use_birthday, use_phone,use_mobile, use_yahoo,use_skype,use_province,use_sex, use_status, use_regisdate, use_enddate";
    	$result = $this->User_model->fetch($select, $where, $sidx, $sord, $start, $limit);
    	$i=0;
    	foreach($result as $userArray)
    	{
    		$responce->rows[$i]['id']=$userArray->use_id;
    		$responce->rows[$i]['name']=$userArray->use_username;
    		$responce->rows[$i]['fullname']=$userArray->use_fullname;
    		$responce->rows[$i]['email']=$userArray->use_email;
    		$responce->rows[$i]['addr']=$userArray->use_address;
    		$responce->rows[$i]['phone']=$userArray->use_phone;
    		$responce->rows[$i]['mobil']=$userArray->use_mobile;
    		$responce->rows[$i]['birthday']=date("d/m/Y",$userArray->use_birthday);
    		$responce->rows[$i]['yahoo']=$userArray->use_yahoo;
    		$responce->rows[$i]['skype']=$userArray->use_skype;
    		$responce->rows[$i]['gender']=$userArray->use_sex;
    		$responce->rows[$i]['province']=$userArray->use_province;
    		$i++;
    	}
    
    	echo json_encode($responce);
    }
    /*---------------------Ket thuc Xem 1 ban ghi--------------------------*/
    
}
